#!/usr/bin/env python
# -*- coding:utf-8 -*-


'''
@Author : shouke
'''

import logging

from config.config import request_response_field_map
from .assertioner import Assertioner
from components.decoraters.action_decorater import ActionDecorator

logger = logging.getLogger(__name__)


class ResponseAssertioner(Assertioner):
    '''响应断言'''
    @ActionDecorator.action_register('assert_response_default', 'ResponseAssertioner', 'assert_response_default', __name__)
    @classmethod
    def assert_response_default(self, response, *args, **kwargs):
        '''
        默认响应断言
        :param response 请求响应对象
        '''

        if response.status not in [200, 201, 301]:
            response._report_success()
            logger.debug('【请求断言结果】：成功')
        else:
            msg = '状态码(%s)错误' % response.status
            response._report_failure(Exception(msg))
            logger.debug('【请求断言结果】：失败，响应状态码：%s' % response.status)

    @ActionDecorator.action_register('assert_response','ResponseAssertioner', 'assert_response', __name__)
    @classmethod
    def assert_response(self, config:dict, *args, **kwargs):
        '''
        请求响应断言
        :param config 断言配置，具体如下

        {
            "target": "body", # 断言目标，暂时支持body - 响应体,header - 响应头,status - 响应状态码
            "rule": "assert_contain", #模式要匹配的规则,目前支持 assert_contain 包含  assert_equal 等于
            "patterns": ["授客", "token"], # 模式 [模式1，模式2，模式3]
            "logic":"or"， # 模式之间的逻辑关系 and 、or  可不配置logic配置项，默认为and (可选)
            "response":responseObj # 请求响应对象
        }
        '''

        response = config.get('response')
        logger.debug('正在执行请求断言')
        logger.debug('【请求断言对象】：%s' % getattr(response, request_response_field_map[config['target'].lower()]))
        logger.debug('【请求断言匹配规则】：%s' % config['rule'])
        logger.debug('【请求断言模式】：%s' % config['patterns'])
        if config['target'].lower() not in request_response_field_map:
            logger.warn('断言目标对象配置错误，可选值为：%s' % ','.join(list(request_response_field_map.keys())))
            self.assert_response_default(response)
            return
        if getattr(self, config['rule'].lower())(getattr(response, request_response_field_map[config['target'].lower()]), config['patterns'], config.get('logic') or 'and'):
            response._report_success()
            logger.debug('【请求断言结果】：成功')
        else:
            response._report_failure(Exception('断言失败，服务器返回：%s' % response.text))
            logger.debug('【请求断言结果】：失败')

